package com.nicholas.exampleweb.repository;

import com.nicholas.exampleweb.model.User;
import com.nicholas.exampleweb.util.DBManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserRepository implements BaseRepository<User>{

    private Connection connection = DBManager.getConnection();

    public static final String INSERT_USER_DML_SQL = "INSERT INTO users(name,password,email,phoneNumber) VALUES " +
            "(?,?,?,?)";

    public static final  String SELECT_USER_DML_SQL = "SELECT id,name,password,email,phoneNumber FROM users";

    @Override
    public void save(User entity) {
        try {
            PreparedStatement statement = connection.prepareStatement(INSERT_USER_DML_SQL);
            statement.setString(1,entity.getName());
            statement.setString(2, entity.getPassword());
            statement.setString(3, entity.getEmail());
            statement.setString(4, entity.getPhoneNumber());
            int execute = statement.executeUpdate();
            System.out.println(execute);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<User> queryAll() {
        try {
            PreparedStatement statement = connection.prepareStatement(SELECT_USER_DML_SQL);
            ResultSet resultSet = statement.executeQuery();
            List<User> users = new ArrayList<>();
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setName(resultSet.getNString("name"));
                user.setEmail(resultSet.getNString("email"));
                user.setPassword(resultSet.getNString("password"));
                user.setPhoneNumber(resultSet.getNString("phoneNumber"));
                users.add(user);
            }
            return users;
        } catch (
                SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
